<?php

namespace app\api\controller\paotui;

use addons\paotui\library\BaiduApi\AipNlp;
use addons\paotui\library\Map;
use addons\paotui\service\Config as PaotuiConfig;
use app\admin\model\paotui\Config;
use app\admin\model\paotui\GoodsType;
use app\admin\model\paotui\TemplateIds;
use app\admin\model\paotui\Times;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\Db;
use EasyWeChat\Factory;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['nlp_address','get_template_ids','regions','get_poi_nearby','decryptData','times','goods_type','getBPrice','allschool','school_detail','getmenu','allschoollength','upStair','showExpress'];
    protected $noNeedRight = '*';

    /**
     * 获取当前开通城市
     */
    public function city(){
        $this->success("请求成功",PaotuiConfig::get('city'));
    }

    /**
     * 获取模板消息ID
     */
    public function get_template_ids(){
        $code = $this->request->post("code","");
        if(empty($code)){
            $this->success('请求成功',[]);
        }

        $templateIdsModel = new TemplateIds();
        $templateIdsList = $templateIdsModel->where(['code'=>['in',explode(",",$code)]])->column("template_id");

        $this->success('请求成功',$templateIdsList);
    }

    /**
     * 获取保价金额
     */
    public function getBPrice(){
        $b_price = $this->request->post("b_price");
        $postService = new \addons\paotui\service\Post();

        $this->success("请求成功",$postService->getBPrice($b_price));
    }


    /**
     * 小程序解码
     */
    public function decryptData(){

        $configModel = new Config();
        $config = $configModel->where(['group'=>'mini'])->column("name,value");

        $encryptedData = $this->request->request('encryptedData');
        $iv = $this->request->request('iv');
        $code = $this->request->request("code");

        $options = [
            'app_id'   => $config['mini_appid'],
            'secret'   => $config['mini_appsecret'],
        ];

        $app = Factory::miniProgram($options);
        $sns = $app->auth->session($code);

        if(!empty($sns['session_key'])){
            $data = $app->encryptor->decryptData($sns['session_key'],$iv,$encryptedData);
            $this->success("请求成功",$data);
        }else{
            $this->success("请求失败");
        }
    }

    /**
     * 获取预约时间段
     * type 1帮取、帮送
     */
    public function times(){
        $type = $this->request->post("type",1);

        $times = new Times();
        $timesList = $times->where(['type'=>$type])->order("weigh asc")->column("times");
        foreach ($timesList as &$v){
            $v = str_replace(" ","",$v);
        }
        $this->success("请求成功",$timesList);
    }

    /**
     *物品类型
     */
    public function goods_type(){
        $goodsTypeModel = new GoodsType();
        $goodsType = $goodsTypeModel->order("weigh asc")->column('goods_type');

        $this->success('请求成功',$goodsType);
    }


    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }

    /**
     * 智能识别地址
     */
    public function nlp_address(){

        $content = $this->request->post("content");

        $content = str_replace(array("\r\n", "\r", "\n"), " ", $content);

        $configModel = new Config();
        $config = $configModel->where(['group'=>'base'])->column("name,value");

        $appid = $config['bd_appid'];
        $api_key = $config['bd_api_key'];
        $secret_key = $config['bd_secret_key'];

        if(strpos($content,$config['city']) === false){
            $content = str_replace("/",'',$config['city']).$content;
        }

        $client = new AipNlp($appid, $api_key, $secret_key);
        $address = $client->address($content);

        if(!empty($address['city'])){
            $address['province'] = str_replace('北京市',"北京",$address['province']);
            $address['province'] = str_replace('天津市',"天津",$address['province']);
            $address['province'] = str_replace('上海市',"上海",$address['province']);
            $address['province'] = str_replace('重庆市',"重庆",$address['province']);
        }

        $this->success('请求成功',$address);
    }
    /**
     * 获取所有学校
     */
    public function allschool(){
        $po = $this->request->post();
        $city = $po['city'];
       
        $where = [];
       
        if($city){
            $where['province'] = $city[0];
            $where['city'] = $city[1];
        }
         
        $search =$po['search'];
        if($search){
            $where['name'] = ['like','%'.$search.'%'];
        }
       
        $schools = Db::name('school')->where($where)->where('deletetime is null')->select();
        if($schools){
            $this->success('请求成功',$schools);
        }else{
            $this->error('暂无学校');
        }
        
    }
    /**
     * 获取用户学校信息
     * 
     */
    public function allschoollength(){
        $po =  $this->request->post();
        if($po['city']['location']){
            $schools = Db::name('school')->where('deletetime is null')->select();
            $main = 0;
            $maindistance = 0;
            foreach($schools as $k=>&$v){
                $schoolname = Db::name('school')->where(['id'=>$v['school_id']])->find();
                $distance = abs($schoolname['lng']-$po['city']['location']['lng']) + abs($schoolname['lat']-$po['city']['location']['lat']);
                if($k == 0){
                    $maindistance = $distance;
                    $main = $k;
                }else{
                    if($maindistance>$distance){
                        $maindistance = $distance;
                        $main = $k;
                    }
                }
                $v['main'] = 0;
            }
            $schools[$main]['main'] = 1;
        }else{
            $schools = Db::name('school')->where($where)->where('deletetime is null')->select();
        }
        
        
        
        if($schools){
            $this->success('请求成功',$schools);
        }else{
            $this->error('暂无学校');
        }
        
    }
     /**
     * 获取所有楼栋
     */
    public function allbuilding(){
        $po = $this->request->post();
        
        $building = Db::name('building')->where(['school_id'=>$po['id']])->select();
        if($building){
            $this->success('请求成功',$building);
        }else{
            $this->error('暂无学校');
        }
        
    }
    /**
     * 获取菜单
     * @ApiMethod (POST)
     * @param id 菜单类型ID
     * 
     * 
     */
    public function getmenu(){
        $po = $this->request->post();
        $menu = Db::name('masks_options')->where(['options_id'=>$po['id']])->select();
        $this->success('成功',$menu);
    }
    
    
     
    
    /**
     * 获取单个学校信息
     */
    public function school_detail(){
        $po = $this->request->post();
        $schoolinfo = Db::name('school')->where(['id'=>$po['id']])->where('deletetime is null')->find();
       
        $userinfo = Db::name('user_school')->where(['user_id'=>$this->auth->id,'school_id'=>$po['id']])->find();
        
        
        if($userinfo){
            $schoolinfo['user'] = $userinfo;
        }
        $build = Db::name('building')->where(['school_id'=>$po['id']])->select();
        if($build){
            $schoolinfo['build'] = $build;
        }
        if($schoolinfo){
            $this->success('请求成功',$schoolinfo);
        }else{
            $this->error('暂无学校');
        }
        
    }
    
    public function upStair(){
        $site = Config('site');
        if($site['up_stair'] == 1){
			$uid=$this->auth->id;
			if($uid){
				$user=Db::name('user')->where('id',$uid)->find();
				if($user && $user['parent_user_id']){
					$upa=Db::name('shopro_commission_agent')->where('user_id',$user['parent_user_id'])->find();
					if(!$upa || !$upa['up_stair']){
						$this->error('分销商未开启上楼');
					}
				}
			}
			$this->success('已开启上楼',1);
        }else{
            $this->error('未开启上楼');
        }
    }
    public function showExpress(){
        $site = Config('site');
        if($site['showexpress'] == 1){
            $this->success('已开启寄快递',1);
        }else{
            $this->error('未开启寄快递');
        }
    }
    public function userWash(){
        $user = Db::name('user')->where(['id'=>$this->auth->id])->find();
        $this->success('剩余洗衣次数',$user['washnum']);
    }
}   
